/*
 Copyright (c) 2008 TPSi
 Alex Iskander
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 
 */


#include "Selector.h"
#include "BindableObject.h"
#include "Bindable.h"
#include "Bound.h"

#include <iostream>

using namespace Bind;
Selector::Selector()
{
	this->_next = NULL;
	this->autoDeleteNext = false;
}

Bindable *Selector::get(Bindable *object)
{
	/* Get the result */
	Bindable *result = run(object);
	
	//don't waste further processor cycles if we don't have anything
	if (!result) return NULL;
	
	/* If there is a sub-selector, execute if result is BindableObject */
	//it may be wise to turn this recursion into a loop at some point,
	//even though doing so would remove the flexibility offered by the
	//possibility of overriding get().
	
		
	if (this->_next){
		BindableObject *b;
		b = result->getBindableObject();
		
		if (b)
		{
			//we have another processor and an object to process. Process.
			return this->_next->get(b);
		}
		else
		{
			return NULL; //we could not process everything.
		}
	}
	return result;
}

Selector *Selector::next()
{
	//return the next selector in the chain.
	return this->_next;
}

Selector *Selector::next(Selector *selector, bool autoDelete)
{
	/* If there is a next selector, remove it */
	if (this->_next)
	{
		//if we should auto-delete, do so.
		if (this->autoDeleteNext) delete this->_next;
		
		//now set to NULL for safety.
		this->_next = NULL;
	}
	
	/* Set next selector */
	//set the selector
	this->_next = selector;
	
	//set auto delete
	this->autoDeleteNext = autoDelete;
	
	//return the selector
	return selector;
}

Selector::~Selector()
{
	//if we should autodelete and there is something to autodelete, delete _next
	if (autoDeleteNext && _next) delete _next;
	
	//set _next to NULL for safety
	_next = NULL;
}